package com.leedsoft.spittr.aop.proxy_test.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by leeds on 2017/11/15.
 * 动态代理生成类
 */
public class ProxyCreator implements InvocationHandler {
    private BookFacadeImpl target;
    public BookFacade getProxy() {//Proxy获取代理对象
        return (BookFacade) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),
                this);
    }
    public ProxyCreator(BookFacadeImpl target) {
        this.target = target;
    }

    @Override //通知切入点
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("前置逻辑");
        Object result = method.invoke(target, args);//反射机制，调用原方法
        System.out.println("后置逻辑");
        return result;
    }

    public static void main(String[] args) {
        BookFacade bookFacade = new ProxyCreator(new BookFacadeImpl()).getProxy();
        bookFacade.addBook();
    }
}
